<template>
  <view class="latest-messages-page page-content">
    <z-paging ref="paging" v-model="messageList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="false" empty-view-text="暂无消息">
      <template #top>
        <up-navbar title="最新消息" :autoBack="true" :fixed="true" bgColor="transparent" :border="false" placeholder>
        </up-navbar>
      </template>

      <view class="message-list">
        <MessageItem 
          v-for="(item, index) in messageList" 
          :key="index" 
          :message="item" 
          @click="handleMessageClick"
        />
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getLatestMessages } from '@/api';
import MessageItem from './components/MessageItem.vue';

// z-paging 组件引用
const paging = ref(null);

// 消息列表数据
const messageList = ref([]);

// 获取最新消息列表
const queryList = async () => {
  try {
    // 调用API获取最新5条消息
    const result = await getLatestMessages({
      limit: 5 // 限制返回5条最新消息
    });
    
    // 如果后端API尚未实现，使用以下模拟数据进行测试
    if (!result.data || result.data.length === 0) {
      const mockData = [
        {
          id: '1',
          title: '车辆核验任务待处理',
          content: '您有一个新的车辆核验任务需要处理，请及时查看。',
          createTime: '2023-08-15 10:30:25',
          type: 'task',
          status: 'unread',
          targetUrl: '/pages/vehicle-internal-verify/detail',
          targetParams: { taskId: '12345' }
        },
        {
          id: '2',
          title: '系统维护通知',
          content: '系统将于今晚22:00-23:00进行例行维护，请提前做好相关工作安排。',
          createTime: '2023-08-14 16:45:12',
          type: 'notice',
          status: 'read',
          targetUrl: '/pages/user-notice/index',
          targetParams: {}
        },
        {
          id: '3',
          title: '工单处理提醒',
          content: '您有3个工单即将超时，请尽快处理。',
          createTime: '2023-08-14 09:15:30',
          type: 'warning',
          status: 'unread',
          targetUrl: '/pages/work-order/index',
          targetParams: {}
        },
        {
          id: '4',
          title: '车辆申诉待处理',
          content: '有新的车辆申诉需要您审核，请及时处理。',
          createTime: '2023-08-13 14:20:45',
          type: 'task',
          status: 'read',
          targetUrl: '/pages/order-appeal/index',
          targetParams: {}
        },
        {
          id: '5',
          title: '新功能上线通知',
          content: '系统新增"最新消息"功能，方便管理员及时了解待处理事项。',
          createTime: '2023-08-12 11:05:18',
          type: 'notice',
          status: 'read',
          targetUrl: '',
          targetParams: {}
        }
      ];
      paging.value.complete(mockData);
    } else {
      paging.value.complete(result.data || []);
    }
  } catch (error) {
    console.error('获取最新消息失败', error);
    paging.value.complete(false);
  }
};

// 处理消息点击事件
const handleMessageClick = (message) => {
  // 如果有目标URL，则跳转到对应页面
  if (message.targetUrl) {
    // 构建跳转URL，包含参数
    let url = message.targetUrl;
    if (message.targetParams && Object.keys(message.targetParams).length > 0) {
      const params = Object.entries(message.targetParams)
        .map(([key, value]) => `${key}=${value}`)
        .join('&');
      url = `${url}?${params}`;
    }
    
    // 使用redirectTo避免页面堆栈累积
    uni.redirectTo({
      url,
      fail: (err) => {
        console.error('页面跳转失败', err);
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
    
    // 标记消息为已读（实际项目中应调用API更新状态）
    // updateMessageStatus(message.id, 'read');
  }
};



// 页面挂载时获取数据
onMounted(() => {
  // 初始加载数据由z-paging的auto属性自动触发
});
</script>

<style scoped lang="scss">
.latest-messages-page {
  background-color: #f5f5f5;
}

.message-list {
  padding: 20rpx;
}
</style>